//判断是否是正常的从微信浏览器打开的
var isTruePath = false;
var appId = '', openId = '', tel = '', version = '';
if(document.URL.lastIndexOf("?") > 0) {
    var arr = document.URL.substring(document.URL.lastIndexOf("?")+1, document.URL.length).split("&");
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].split("=")[0] == 'appId') {
            appId = arr[i].split("=")[1];
        } else if (arr[i].split("=")[0] == 'openId') {
            openId = arr[i].split("=")[1];
        } else if (arr[i].split("=")[0] == 'tel') {
            tel = arr[i].split("=")[1].split("#")[0];
        } else if (arr[i].split("=")[0] == 'v5') {
            version = arr[i].split("=")[0];
        }
    }
}
function isWechat(){
    return navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger";
}
window.onload = function() {
    isTruePath = !(appId == '' || openId == '' || tel == '' || isWechat() == false);
    if (isTruePath && !version) {
        window.location.href = document.URL + '&v5';
    }
};

var canvasWidth = 720, canvasHeight = 1280;
init(50,"findWord",canvasWidth,canvasHeight,main);

var loadingLayer, baseLayer, backLayer, gameBackLayer, gameLayer;
var maskLayer, popupLayer, popupMsgLeft = 57, popupMsgTop = 290, popupMsgLineHeight = 50, popupBtnTop = 480;
var imgList = {};
var imgData = [
    {name:"imgBg", path:"img/bg.jpg"},
    {name:"img4C", path:"img/4C.png"},
    {name:"img4G", path:"img/4G.png"},
    {name:"imgShare", path:"img/share.png"},
    {name:"imgStart", path:"img/btnStart.png"},
    {name:"imgScore", path:"img/btnScore.png"},
    {name:"imgOk", path:"img/btnOk.png"},
    {name:"imgCancel", path:"img/btnCancel.png"},
    {name:"imgRePlay", path:"img/btnRePlay.png"},
    {name:"imgClose", path:"img/btnClose.png"},
    {name:"imgBgTimer", path:"img/bgTimer.png"},
    {name:"imgRule", path:"img/btnRule.png"},
    {name:"imgMemberCode", path:"img/btnMemberCode.png"},
    {name:"imgScoreDisable", path:"img/btnScoreDisable.png"}
];
var tfScore, score = 0;
var tfTimer, toolTimer, maxTimeout = 40, timer = maxTimeout;
var btnStart, btnScore, btnRule, btnMemberCode;
var maxPlayRound = -1, currentPlayRound = 1;

var gridSize = 2, maxGridSize = 7, playTimes = 0;
var gameLayerLeft = 19, gameLayerTop = 380, tileMargin = 8;
var tileSize, oldTileSize = (canvasWidth - 2 * gameLayerLeft - 3 * tileMargin) / 2;

var i0, j0;
function randomAim() {
    i0 = Math.floor(Math.random()*gridSize);
    j0 = Math.floor(Math.random()*gridSize);
}
var tileBgColors = ["#f89722", "#ed4901", "#ed3969", "#e3014d", "#e200004", "#b90010", "#830010", "#52070c",
    "#1b0a2a", "#04b012", "#006293", "#0a4885", "#3a0231", "#146f1f", "#5eb92d", "#17a833", "#014421", "#f47200",
    "#ad011b", "#261911", "#3a332d", "#574b3d", "#b49d7d"];
function randomColor() {
    return tileBgColors[Math.floor(Math.random() * tileBgColors.length)];
}

var urlRule = "http://mp.weixin.qq.com/s?__biz=MzA4NzQ1NjUxMg==&mid=205919522&idx=1&sn=1b2d3dc0a15fe17f8286c38115b22e5f#rd";
var urlMemberCode = "http://mp.weixin.qq.com/s?__biz=MzA4NzQ1NjUxMg==&mid=205773600&idx=1&sn=d8e43a69bf7fcab127a737be1f5f1d65#rd";

function main() {
    LGlobal.stageScale = LStageScaleMode.EXACT_FIT;
    LSystem.screen(LStage.FULL_SCREEN);
    LGlobal.stage.addEventListener(LEvent.WINDOW_RESIZE, windowResize);

    loadingLayer = new LoadingSample3();
    addChild(loadingLayer);
    LLoadManage.load(imgData, function(progress){
        loadingLayer.setProgress(progress);
    }, gameInit);
}

function windowResize() {
    LGlobal.stageScale = LStageScaleMode.EXACT_FIT;
    LSystem.screen(LStage.FULL_SCREEN);
}

function gameInit(result) {
    imgList = result;
    if(isTruePath) {
        LAjax.post("/rest/findWord/init", {"appId": appId, "openId": openId, "tel": tel}, function (data) {
            data = eval('(' + data + ')');
            timer = maxTimeout = data.timeout;
            maxPlayRound = data.maxRound;
            currentPlayRound = data.currentRound;

            gameInitNow();
        });
    } else {
        gameInitNow();
    }
}
function gameInitNow() {
    removeChild(loadingLayer);
    loadingLayer = null;

    baseLayer = new LSprite();
    addChild(baseLayer);

    backLayer = new LSprite();
    baseLayer.addChild(backLayer);
    backLayer.addChild(buildBitmap("imgBg"));
    tfScore = buildTextField(score, 142, 178, 50, "red");
    backLayer.addChild(tfScore);
    if(maxPlayRound == -1 && maxTimeout == 60) {
        backLayer.addChild(buildBitmap("imgBgTimer", 569, 160));
    }
    tfTimer = buildTextField(timer, 603, 182, 40);
    backLayer.addChild(tfTimer);
    btnScore = buildButton(buildBitmap("imgScore"), 17, 1130, getScore, buildBitmap("imgScoreDisable"));
    backLayer.addChild(btnScore);
    btnRule = buildButton(buildBitmap("imgRule"), 250, 1130, function(){window.location = urlRule;});
    backLayer.addChild(btnRule);
    btnMemberCode = buildButton(buildBitmap("imgMemberCode"), 483, 1130, function(){window.location = urlMemberCode;});
    backLayer.addChild(btnMemberCode);
    if(!isTruePath) {
        btnScore.setState(LButton.STATE_DISABLE);
    }

    gameBackLayer = new LSprite();
    baseLayer.addChild(gameBackLayer);
    gameBackLayer.graphics.drawRoundRect(0, "white",
        [gameLayerLeft, gameLayerTop, canvasWidth - 2 * gameLayerLeft, canvasWidth - 2 * gameLayerLeft, 15],
        true, "white");

    gameLayer = new LSprite();
    gameBackLayer.addChild(gameLayer);
    initGameLayer(true);

    maskLayer = new LSprite();
}
function startGame() {
    btnStart.remove();
    btnScore.remove();
    btnRule.remove();
    btnMemberCode.remove();

    if(!isTruePath) {
        showPopup(function(layer){
            layer.addChild(buildTextField("请先关注【内蒙古移动营业厅】公", popupMsgLeft, popupMsgTop));
            layer.addChild(buildTextField("众微信账号，否则成绩无法计入排", popupMsgLeft, popupMsgTop + popupMsgLineHeight));
            layer.addChild(buildTextField("名赢话费哦~", popupMsgLeft, popupMsgTop + 2 * popupMsgLineHeight));
            layer.addChild(buildButton(buildBitmap("imgOk"), popupMsgLeft, popupBtnTop, function(){closePopup(); startGameNow();}));
            layer.addChild(buildButton(buildBitmap("imgRule"), popupMsgLeft + 310, popupBtnTop, function(){window.location = urlRule;}));
        });
    } else {
        startGameNow();
    }
}
function startGameNow(isReplay) {
    window.document.title = "新春找4G，全民抢话费";
    if(isTruePath) {
        if(currentPlayRound == -2) {
            showPopup(function(layer) {
                var tip1 = "当前活动已经结束";
                var tip2 = "请重新输入找4G参与新活动~";
                layer.addChild(buildTextField(tip1, popupMsgLeft, popupMsgTop));
                layer.addChild(buildTextField(tip2, popupMsgLeft, popupMsgTop + popupMsgLineHeight));
                layer.addChild(buildButton(buildBitmap("imgClose"), (canvasWidth - 290) / 2, popupBtnTop, closeWeb));
            });
            return;
        }
        if(currentPlayRound == -1) {
            showPopup(function(layer) {
                var tip1 = "您的手机"+ tel +"已经中奖，";
                var tip2 = "请更换手机号继续参与~";
                layer.addChild(buildTextField(tip1, popupMsgLeft, popupMsgTop));
                layer.addChild(buildTextField(tip2, popupMsgLeft, popupMsgTop + popupMsgLineHeight));
                layer.addChild(buildButton(buildBitmap("imgClose"), (canvasWidth - 290) / 2, popupBtnTop, closeWeb));
            });
            return;
        }
        if(maxPlayRound != -1 && currentPlayRound > maxPlayRound) {
            var tip = maxPlayRound == 1 ? "您可以领取升级码获得一个额外次数" : "您今天的游戏次数已达到上限";
            if(isReplay) {
                showPopup(function(layer) {
                    layer.removeChildAt(layer.numChildren - 1);
                    layer.addChild(buildTextField("(" + tip + ")", popupMsgLeft + 10, popupMsgTop + 2 * popupMsgLineHeight, 25, "yellow"));
                    layer.addChild(buildButton(buildBitmap("imgMemberCode"), popupMsgLeft + 310, popupBtnTop, function(){
                        if(maxPlayRound == 1) {
                            window.location = urlMemberCode;
                        } else {
                            closeWeb();
                        }
                    }));
                }, true);
            } else {
                showPopup(function (layer) {
                    layer.addChild(buildTextField(tip, popupMsgLeft, popupMsgTop + popupMsgLineHeight));
                    layer.addChild(buildButton(buildBitmap("imgClose"), (canvasWidth - 290) / 2, popupBtnTop, closeWeb));
                });
            }
            return;
        }
    }

    if(isReplay) {
        closePopup();
    }
    initGameLayer();
    toolTimer = setInterval(function () {drawTimer();}, 1000);
}
function drawTimer(){
    tfTimer.text = --timer < 10 ? "0" + timer : timer;
    tfTimer.color = timer < 10 ? "yellow" : "white";
    if(timer <= 0) {
        gameLayer.removeAllEventListener();
        clearInterval(toolTimer);
        gameOver();
    }
}
function getScore(isStart) {
    if(isTruePath) {
        btnScore.setState(LButton.STATE_DISABLE);
        LAjax.post("/rest/findWord/score", {"tel": tel}, function (data) {
            data = eval('(' + data + ')');
            var telephone = data.tel;
            var finishTime = data.finishTime;
            var ranking = data.rownum;
            var prize = data.prize;
            var result = data.result;

            var tip1 = "", tip2 = "", tip3 = "";
            if(ranking) {
                if(ranking == -1) {
                    tip1 = "哦~还是慢了点，没进入全区前2万";
                    tip2 = "名，擦擦手汗再来一遍！";
                } else {
                    tip1 = "恭喜！您的手机号" + telephone;
                    tip2 = "在" + format(finishTime, 'yyyy年MM月dd日') + "找到" + result + "个4G";
                    tip3 = "目前全区排名为第"+ranking+"名";
                }
            } else if(prize) {
                if(prize == -1) {
                    tip1 = "您未中奖，请继续努力~";
                } else {
                    tip1 = "您的手机号" + telephone;
                    tip2 = "在" + format(finishTime, 'yyyy年MM月dd日') + "找到" + result + "个4G";
                    tip3 = "获得"+prize+"元话费";
                }
            }

            if(isStart) {
                showPopup(function (layer) {
                    layer.addChild(buildTextField(tip1, popupMsgLeft, popupMsgTop));
                    layer.addChild(buildTextField(tip2, popupMsgLeft, popupMsgTop + popupMsgLineHeight));
                    layer.addChild(buildTextField(tip3, popupMsgLeft, popupMsgTop + 2 * popupMsgLineHeight));
                    layer.addChild(buildButton(buildBitmap("imgOk"), (canvasWidth - 290) / 2, popupBtnTop, function () {
                        closePopup();
                    }));
                });
            } else {
                showPopupWithoutMask(function (layer) {
                    layer.addChild(buildTextField(tip1, popupMsgLeft, popupMsgTop));
                    layer.addChild(buildTextField(tip2, popupMsgLeft, popupMsgTop + popupMsgLineHeight));
                    layer.addChild(buildTextField(tip3, popupMsgLeft, popupMsgTop + 2 * popupMsgLineHeight));
                    layer.addChild(buildButton(buildBitmap("imgOk"), (canvasWidth - 290) / 2, popupBtnTop, function () {
                        closePopup(true);
                    }));
                });
            }

            btnScore.setState(LButton.STATE_ENABLE);
        });
    }
}
function initGameLayer(isFirstTime) {
    gameLayer.removeAllChild();
    gameLayer.die();

    tileSize = (canvasWidth - 2 * gameLayerLeft - (gridSize + 1) * tileMargin) / gridSize;
    randomAim();
    var color = randomColor();
    for (var i = 0; i < gridSize; i++) {
        for (var j = 0; j < gridSize; j++) {
            if(i == i0 && j == j0) {
                drawTile(gameLayer, "img4G", color, tileSize, i, j);
            } else {
                drawTile(gameLayer, "img4C", color, tileSize, i, j);
            }
        }
    }
    if(!isFirstTime) {
        gameLayer.addEventListener(LMouseEvent.MOUSE_DOWN, clickTile);

        playTimes++;
        if(gridSize == playTimes && gridSize < maxGridSize) {
            playTimes = 0;
            gridSize++;
        }
    } else {
        btnStart = buildButton(buildBitmap("imgStart"), 0, gameLayerTop, startGame);
        gameLayer.addChild(btnStart);
    }
}
function drawTile(layer, img, color, size, i, j) {
    var posX = gameLayerLeft + (i + 1) * tileMargin + i * tileSize;
    var posY = gameLayerTop + (j + 1) * tileMargin + j * tileSize;
    layer.graphics.drawRoundRect(0, "white", [posX, posY, size, size, 15], true, color);
    layer.addChild(buildBitmap(img, posX, posY, tileSize / oldTileSize));
}
function clickTile(event) {
    var partX = Math.floor((event.offsetX - gameLayerLeft - tileMargin) / (tileSize + tileMargin));
    var partY = Math.floor((event.offsetY - gameLayerTop - tileMargin) / (tileSize + tileMargin));
    if(partX==i0 && partY==j0){
        tfScore.text = ++score;
        initGameLayer();
    }
}
function gameOver() {
    currentPlayRound++;
    if(isTruePath) {
        LAjax.post("/rest/findWord/save", {
            "score": score,
            "appId": appId,
            "openId": openId,
            "tel": tel,
            "sign": 'v99'
        });
    }
    showPopup(function(layer) {
        var tfMsg1 = buildTextField("您找到了", popupMsgLeft, popupMsgTop);
        var tfMsg2 = buildTextField(score, popupMsgLeft + tfMsg1.getWidth() + 8, popupMsgTop - 10, 40, "#FBFF26");
        var tfMsg3 = buildTextField("个4G", popupMsgLeft + tfMsg1.getWidth() + 16 + tfMsg2.getWidth(), popupMsgTop);
        layer.addChild(tfMsg1);
        layer.addChild(tfMsg2);
        layer.addChild(tfMsg3);
        layer.addChild(buildTextField("快到朋友圈里炫耀一下吧！", popupMsgLeft, 340));
        if(maxPlayRound == -1 && maxTimeout == 40) {
            layer.addChild(buildTextField("您可以领取【时间代码】获得额外20秒游戏时间", popupMsgLeft, popupMsgTop + 2 * popupMsgLineHeight, 22, "yellow"));
        }
        layer.addChild(buildButton(buildBitmap("imgOk"), popupMsgLeft, popupBtnTop, function(){
            closePopup(true);
            baseLayer.addChild(buildBitmap("imgShare"));
            window.document.title = "快来参与找4G赢话费游戏，我一共找了" + score + "个4G，你也来挑战吧~";

            layer.addChild(btnRule);
            layer.addChild(btnMemberCode);
            layer.addChild(btnScore);
            if(!isTruePath) {
                btnScore.setState(LButton.STATE_DISABLE);
            }
            btnRule.addEventListener(LMouseEvent.MOUSE_UP, function(){window.location = urlRule;});
            btnMemberCode.addEventListener(LMouseEvent.MOUSE_UP, function(){window.location = urlMemberCode;});
            btnScore.removeAllEventListener();
            btnScore.addEventListener(LMouseEvent.MOUSE_UP, function(){getScore(false);});
        }));
        layer.addChild(buildButton(buildBitmap("imgRePlay"), popupMsgLeft + 310, popupBtnTop, function(){

            gridSize = 2;
            playTimes = 0;
            score = 0;
            timer = maxTimeout;
            tfScore.text = score;
            tfTimer.text = timer;
            startGameNow(true);
        }));
    });
}

function showPopup(fnContent, isChangeContent) {
    if(!isChangeContent) {
        maskLayer.graphics.drawRect(0, "white", [0, 0, canvasWidth, canvasHeight], true, "#fcad26");
        maskLayer.alpha = 0.8;
        baseLayer.addChild(maskLayer);

        popupLayer = new LSprite();
        popupLayer.graphics.drawRoundRect(10, "white", [17, 250, 686, 350, 15], true, "red");
        baseLayer.addChild(popupLayer);
    }

    fnContent(popupLayer);
}

function showPopupWithoutMask(fnContent) {
    popupLayer = new LSprite();
    popupLayer.graphics.drawRoundRect(10, "white", [17, 250, 686, 350, 15], true, "red");
    baseLayer.addChild(popupLayer);
    fnContent(popupLayer);
}

function closePopup(keepMask) {
    if(popupLayer) {
        popupLayer.removeAllChild();
        popupLayer.die();
    }
    if(!keepMask) {
        maskLayer.die();
    }
}

function buildTextField(text, x, y, size, color) {
    var textField = new LTextField();
    textField.weight = "bold";
    textField.text = text;
    textField.x = x ? x : 0;
    textField.y = y ? y : 0;
    textField.size = size ? size : 30;
    textField.color = color ? color : "white";
    return textField;
}

function buildButton(bitmap, x, y, fnEvent, disableBitmap) {
    var button = new LButton(bitmap, bitmap, bitmap, disableBitmap);
    button.x = x ? x : 0;
    button.y = y ? y : 0;
    button.addEventListener(LMouseEvent.MOUSE_UP, fnEvent);
    return button;
}

function buildBitmap(imgName, x, y, scale) {
    var bitmap = new LBitmap(new LBitmapData(imgList[imgName]));
    bitmap.x = x ? x : 0;
    bitmap.y = y ? y : 0;
    scale = scale ? scale : 1;
    bitmap.scaleX = scale;
    bitmap.scaleY = scale;
    return bitmap;
}

//分享朋友圈或发送给好友
var imgUrl = "http://103.227.80.253/game/findWord/img/icon.png";
var lineLink = "http://103.227.80.253/game/findWord/index.html";
var shareTitle = "移动找4G";
var descContent = "";
function closeWeb() {
    WeixinJSBridge.invoke('closeWindow', {}, function (res) {});
}

function shareFriend() {
    descContent = "快来参与找4G赢话费游戏，我一共找了" + score + "个4G，你也来挑战吧~";
    WeixinJSBridge.invoke('sendAppMessage', {
        "appid": appId,
        "img_url": imgUrl,
        "img_width": "640",
        "img_height": "640",
        "link": lineLink,
        "desc": descContent,
        "title": shareTitle
    }, function (res) {
        //_report('send_msg', res.err_msg);
    });
    closeWeb();
}

function shareTimeline() {
    descContent = "快来参与找4G赢话费游戏，我一共找了" + score + "个4G，你也来挑战吧~";
    WeixinJSBridge.invoke('shareTimeline', {
        "appid": appId,
        "img_url": imgUrl,
        "img_width": "640",
        "img_height": "640",
        "link": lineLink,
        "desc": descContent,
        "title": descContent
    }, function (res) {
        _report('timeline', res.err_msg);
    });
    closeWeb();
}

//当微信内置浏览器完成内部初始化后会触发WeixinJSBridgeReady事件。
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
    WeixinJSBridge.on('menu:share:appmessage', function (argv) {
        shareFriend();
    });
    WeixinJSBridge.on('menu:share:timeline', function (argv) {
        shareTimeline();
    });
}, false);

//格式化日期
var format = function (time, format) {
    var t = new Date(time);
    var tf = function (i) {
        return (i < 10 ? '0' : '') + i
    };
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
        switch (a) {
            case 'yyyy':
                return tf(t.getFullYear());
                break;
            case 'MM':
                return tf(t.getMonth() + 1);
                break;
            case 'mm':
                return tf(t.getMinutes());
                break;
            case 'dd':
                return tf(t.getDate());
                break;
            case 'HH':
                return tf(t.getHours());
                break;
            case 'ss':
                return tf(t.getSeconds());
                break;
        }
    });
};
